function EEG_weight_sampling(positive_data_matrices,negative_data_matrices,file_weights_data, ...
                                           positive_folder_path,negative_folder_path, ...
                                           target_frame,sampling_rate,num_samples,sampling_counts)
%{
    target_frame=4;
    sampling_rate=256;
    num_samples=10000;
    sampling_counts =10; 
    % 指定文件夹路径
    positive_folder_path = './positive';
    % 指定文件夹路径
    negative_folder_path = './negative';
    
    % 从外部文件加载文件权重
    external_weights_file = './positive_file_weights.csv';
%}
    %file_weights_data = readtable(external_weights_file);
    file_weights = file_weights_data.FileWeight;
    % 设置样本长度
    target_frame_count = target_frame*sampling_rate;
    
    positive_sample_tables = cell(sampling_counts, 1); % 存储每次迭代的 sample_table
    positive_random_samples = cell(sampling_counts, 1); % 存储每次迭代的 random_samples
    negative_sample_tables = cell(sampling_counts, 1); % 存储每次迭代的 sample_table
    negative_random_samples = cell(sampling_counts, 1); % 存储每次迭代的 random_samples
    % 预加载positive .mat文件的数据
    positive_mat_files = dir(fullfile(positive_folder_path, '*.mat'));
%{
    positive_data_matrices = cell(1, numel(positive_mat_files));
    parfor file_index = 1:numel(positive_mat_files)
        file_path = fullfile(positive_folder_path, positive_mat_files(file_index).name);
        loaded_data = load(file_path);
        positive_data_matrices{file_index} = loaded_data.data;
    end
%}
    % 预加载所有negative .mat文件的数据
    negative_mat_files = dir(fullfile(negative_folder_path, '*.mat'));
%{
    negative_data_matrices = cell(1, numel(negative_mat_files));
    parfor file_index = 1:numel(negative_mat_files)
        file_path = fullfile(negative_folder_path, negative_mat_files(file_index).name);
        loaded_data = load(file_path);
        negative_data_matrices{file_index} = loaded_data.data;
    end
%}
    h = waitbar(0, 'Processing...'); 
    for sampling_index = 1:sampling_counts
    %% 阳性样本处理模块结束
        % 初始化存储随机样本的单元数组
        current_row = 1;
        % 初始化存储随机样本的table
        sample_table = table('Size', [num_samples, 5], 'VariableTypes', {'string','string','double', 'double','double'}, ...
                                                       'VariableNames', {'Subject','FileName','start_index', 'end_index', 'FrameNumber'});
        random_samples = cell(1, num_samples);
        % 循环生成随机样本
        for sample_index = 1:length(positive_mat_files)
            % 获取数据矩阵
            data_matrix = positive_data_matrices{sample_index}; % 使用预加载的数据矩阵
            
            % 获取当前文件的权重
            file_weight = file_weights(sample_index);
            % 计算当前文件需要选取的数据段数量
            num_segments = round(file_weight * num_samples);
            % 随机选取数据段
            for segment_index = 1:num_segments
                % 获取数据矩阵的帧数
                matrix_frame_count = size(data_matrix, 2);
                % 随机生成起始索引
                start_index = randi(matrix_frame_count - target_frame_count + 1); 
                % 计算对应的结束索引
                end_index = start_index + target_frame_count - 1;
                % 从数据矩阵中提取随机样本
                random_sample = data_matrix(:, start_index:end_index); 
                % 存储随机样本的起始坐标和文件名到table
                 % 存储文件名的前五位到 Subject 列
                sample_table.Subject{current_row} = extractPatientID(positive_mat_files(sample_index).name);
                sample_table.FileName{current_row} = positive_mat_files(sample_index).name;
                sample_table.start_index(current_row) = start_index;
                sample_table.end_index(current_row) = end_index;
                sample_table.FrameNumber(current_row) = end_index-start_index+1;
                % 存储随机样本
                random_samples{current_row} = random_sample;
                % 更新当前行索引
                current_row = current_row + 1;
            end
        end
        
        % 计算实际样本数量与 num_samples 之间的差值
        actual_total_samples = current_row-1;
        sample_difference = num_samples - actual_total_samples;
        disp(length(positive_mat_files))
        % 根据权重随机选择一个 .mat 文件
        if sample_difference > 0
            selected_file_index = randsample(length(positive_mat_files), sample_difference, true, file_weights);
        
            % 循环处理每个选定的文件索引
            for idx = 1:length(selected_file_index)
                % 获取当前文件的索引
                file_index = selected_file_index(idx);
        
                % 获取当前文件的 .mat 文件名
                file_name = positive_mat_files(file_index).name;
        
                % 获取当前文件的数据矩阵
                data_matrix = positive_data_matrices{file_index}; % 使用预加载的数据矩阵
        
                % 获取数据矩阵的帧数
                matrix_frame_count = size(data_matrix, 2);
        
                % 随机生成起始索引
                start_index = randi(matrix_frame_count - target_frame_count + 1);
        
                % 计算对应的结束索引
                end_index = start_index + target_frame_count - 1;
        
                % 从数据矩阵中提取随机样本
                random_sample = data_matrix(:, start_index:end_index);
        
                % 存储随机样本
                random_samples{current_row} = random_sample;
        
                % 存储随机样本的起始坐标和文件名到 table
                sample_table.Subject{current_row} = extractPatientID(file_name);
                sample_table.FileName{current_row} = file_name;
                sample_table.start_index(current_row) = start_index;
                sample_table.end_index(current_row) = end_index;
                sample_table.FrameNumber(current_row) = end_index - start_index + 1;
        
                % 更新当前行索引
                current_row = current_row + 1;
            end
        elseif sample_difference < 0
            
            % 确定要删除的记录数量
            num_records_to_remove = abs(sample_difference);
            % 随机选择要删除的记录索引
            records_to_remove_indices = randperm(actual_total_samples, num_records_to_remove);
            % 从 sample_table 中删除相应的行
            sample_table(records_to_remove_indices, :) = [];
            % 从 random_samples 中删除相应的元素
            random_samples(records_to_remove_indices) = [];
        end
        random_samples=random_samples.';
        % 保存每次迭代的 sample_table 和 random_samples
        positive_sample_tables{sampling_index} = sample_table;
        positive_random_samples{sampling_index} = random_samples;
        %writetable(sample_table, 'positive_sample.xlsx');
        % 根据 Subject 列的值对 sample_table 进行分组
        grouped_table = findgroups(sample_table.Subject);
        % 创建一个新的 table 包含 subject_value 和 sum(group_indices) 列
        summary_table = table('Size', [max(grouped_table), 2], 'VariableTypes', {'string','double', }, ...
                                                     'VariableNames', {'Subject','SampleCount'});
        % 定义保存文件的基本文件夹
        base_folder = 'positive';
        % 遍历每个分组
        for group_index = 1:max(grouped_table)
            % 获取当前分组的索引
            group_indices = grouped_table == group_index;
            % 获取当前分组的 Subject 值
            subject_value = sample_table.Subject{find(group_indices, 1)};
            % 提取当前分组对应的随机样本数据
            group_samples = random_samples(group_indices);
            
            summary_table.Subject{group_index}=subject_value;
            summary_table.SampleCount(group_index)=sum(group_indices);
            % 生成保存文件夹的路径，包含 num_samples
            folder_name = sprintf('%s_%d_samples_%d', base_folder, num_samples, sampling_index);
            % 如果文件夹不存在，则创建
            if ~exist(folder_name, 'dir')
                mkdir(folder_name);
            end
            % 生成保存文件名
            output_file_name = sprintf('%s_positive_%d.mat', subject_value, sum(group_indices));
        
            % 保存数据为 .mat 文件
            save(fullfile(folder_name,output_file_name), 'group_samples', '-v7.3');
        end
        %writetable(summary_table, 'sample_counts.xlsx');
    
        %{
        % 统计每个文件被选中的次数
        file_counts = zeros(size(positive_mat_files));
        
            % 遍历样本表，统计每个文件被选中的次数
        for i = 1:size(sample_table, 1)
            file_index = find(strcmp({positive_mat_files.name}, sample_table.FileName{i}));
            file_counts(file_index) = file_counts(file_index) + 1;
        end
        
        % 绘制选中次数与权重比较的图表
        figure;
        bar(1:length(positive_mat_files), file_counts);
        hold on;
        plot(1:length(positive_mat_files), file_weights * sum(file_counts), 'r--', 'LineWidth', 2);
        xticks(1:length(positive_mat_files));
        xticklabels({positive_mat_files.name});
        xlabel('文件');
        ylabel('选中次数');
        title('文件选中次数与权重比较');
        legend({'选中次数', '权重'}, 'Location', 'northwest');
        grid on;
        %}
    %% 阳性样本处理模块结束
    
    %% 阴性样本处理模块开始
    
    % 读取样本数量信息
    sample_counts_data = summary_table;
    
    
    % 初始化存储随机样本的table
    sample_table = table('Size', [num_samples, 5], 'VariableTypes', {'string','string','double', 'double','double'}, ...
                                                 'VariableNames', {'Subject','FileName','start_index', 'end_index', 'FrameNumber'});
    % 初始化存储随机样本的单元数组
    random_samples = cell(1, num_samples);
    
    current_row = 1;
    % 遍历每个主题
    subject_files_names = {negative_mat_files.name};
    
    for subject_index = 1:size(sample_counts_data, 1)
        % 获取当前主题
        subject_value = sample_counts_data.Subject(subject_index);
        % 获取当前主题的样本数量
        sample_count = sample_counts_data.SampleCount(subject_index);
        
        % 根据当前主题的样本数量，随机选择相应数量的文件
        % 获取符合主题的文件名数组
    
        subject_files_indices = find(strcmp(cellfun(@extractPatientID, subject_files_names, 'UniformOutput', false), subject_value));
        if numel(subject_files_indices) == 1
        % 如果只有一个文件符合主题，则重复选择这个文件
            selected_file_indices = repmat(subject_files_indices, 1, sample_count);
        else
            % 否则，进行正常的随机抽样
            selected_file_indices = randsample(subject_files_indices', sample_count, true);
        end
    
        % 对选中的文件进行处理
        for file_index = 1:length(selected_file_indices)
            % 获取当前文件索引
            current_file_index = selected_file_indices(file_index);
            
            % 获取当前文件的文件名和数据矩阵
            current_file_name = negative_mat_files(current_file_index).name;
            current_data_matrix = negative_data_matrices{current_file_index};
            
            % 计算当前文件的帧数
            matrix_frame_count = size(current_data_matrix, 2);
            
            % 随机生成起始索引
            start_index = randi(matrix_frame_count - target_frame * sampling_rate + 1);
            end_index = start_index + target_frame * sampling_rate - 1;
            
            % 提取随机样本数据
            random_sample = current_data_matrix(:, start_index:end_index);
            
            % 存储随机样本和相关信息到table
            sample_table.Subject{current_row} = extractPatientID(current_file_name);
            sample_table.FileName{current_row} = current_file_name;
            sample_table.start_index(current_row) = start_index;
            sample_table.end_index(current_row) = end_index;
            sample_table.FrameNumber(current_row) = end_index - start_index + 1;
            random_samples{current_row} = random_sample;
    
            current_row=current_row+1;
        end
    end
        %writetable(sample_table, 'negative_sample.xlsx');
        random_samples=random_samples.';
        negative_sample_tables{sampling_index} = sample_table;
        negative_random_samples{sampling_index} = random_samples;
    
    
    % 根据 Subject 列的值对 sample_table 进行分组
    grouped_table = findgroups(sample_table.Subject);
    % 定义保存文件的基本文件夹
    base_folder = 'negative';
    % 遍历每个分组
    for group_index = 1:max(grouped_table)
        % 获取当前分组的索引
        group_indices = grouped_table == group_index;
        % 获取当前分组的 Subject 值
        subject_value = sample_table.Subject{find(group_indices, 1)};
        % 提取当前分组对应的随机样本数据
        group_samples = random_samples(group_indices);
        folder_name = sprintf('%s_%d_samples_%d', base_folder, num_samples, sampling_index);
        % 如果文件夹不存在，则创建
           if ~exist(folder_name, 'dir')
                mkdir(folder_name);
           end
        % 生成保存文件名
        output_file_name = sprintf('%s_negative_%d.mat', subject_value, sum(group_indices));
        % 保存数据为 .mat 文件
        save(fullfile(folder_name,output_file_name), 'group_samples', '-v7.3');
    end
    
        waitbar(sampling_index / sampling_counts, h, sprintf('Data Processing... %d/%d', sampling_index, sampling_counts));
    end
    % 将结果写入 Excel 文件
    for i = 1:length(positive_sample_tables)
        writetable(positive_sample_tables{i}, sprintf('positive_sample_table_%d.xlsx', i));
    end
    
    for i = 1:length(negative_sample_tables)
        writetable(negative_sample_tables{i}, sprintf('negative_sample_table_%d.xlsx', i));
    end
    % 关闭进度条
    close(h);
    function patient_id = extractPatientID(file_name)
        % 提取文件名中的患者信息
        parts = strsplit(file_name, '_');
        patient_id = parts{1}; % 假设患者信息在文件名的前五位
        %% 因为mit数据集存在chb17a、chb17b、chb17c 针对mit数据集 暂时先取前5位的值
        patient_id = patient_id(1:min(5, numel(patient_id)));
    end
end